<template>
  <div class="applicationcode" @click="goback">
    <header-bar
      v-if="!$route.meta.hideHeader"
      ref="header"
      :title="title"
    >
      <template v-if="$store.state.user.show">
        <svg-icon icon-class="change" class="add" @click.native="changeLocation" />
      </template>
    </header-bar>
    <van-search
      v-if="true"
      v-model="value"
      style="z-index:888;"
      show-action
      placeholder="请输入名称或证件号"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div id="content" ref="order" style="position:relative;" class="content">

      <van-pull-refresh v-model="refreshing" success-text="刷新成功" @refresh="onRefresh">
        <van-list
          v-if="list.length!==0"
          v-model="loading"
          :finished="finished"
          :finished-text="listText"
          :immediate-check="false"
          @load="pageInfoList"
        >

          <van-swipe-cell
            v-for="(item
                    ,index) in list"
            :key="index"
          >
            <van-checkbox-group v-model="result">

              <div style="" :class="[index===0?'order-msg':'',!item.quarantStatus?'order-color':'']" class="order-content">

                <div class="order-title" style="display:flex;justify-content:space-between;">

                  <div class="content-message" style="display:flex;align-items:center;"><div class="chiooce-order"><van-checkbox v-if="item.quarantStatus" :name="item.id" /></div>序号：<div class="number">{{ index+1 }}</div></div>
                  <div style="display:flex;align-items:center;">
                    <svg-icon class="edite" :icon-class="[item.quarantStatus?'edite':'edites']" @click.native="getPerson(item.id,item.quarantStatus)" />
                    <svg-icon :icon-class="[item.quarantStatus?'delete':'deletes']" class="delete" @click.native="deleteInfo(item.id,index,item.quarantStatus)" />

                  </div>

                </div>
                <div class="content-message"><div>姓名：</div><div>{{ item.name }}</div></div>
                <div class="content-message"><div>隔离开始日期：</div><div>{{ item.startTime }}</div></div>
                <div v-if="item.quarantStatus" class="content-message"><div>隔离结束日期：</div><div>{{ item.endTime }}</div></div>
                <div v-else class="content-message"><div>实际解除时间</div><div>{{ item.realTime }}</div></div>
                <div class="content-message reson"><div style="flex:1.5;"><div>隔离原因：</div></div><div style="flex:3;">{{ item.quarantReason }}</div></div>

              </div>
            </van-checkbox-group>
          </van-swipe-cell>

        </van-list>
        <van-empty v-else description="暂无数据" />
      </van-pull-refresh>
      <div style="width:100%;height:260px;" :class="[showTitlePaddingTop?'title-message':'']" />
    </div>
    <div>
      <van-tabbar v-model="active" placeholder safe-area-inset-bottom @change="onChange">
        <div class="content-footer" style="display:flex;align-items:center;width:100%;justify-content:space-around;">
          <van-button type="info" style="border-radius:5px;" size="small" :disabled="clockState" @click="queryClick">健康签到</van-button>
          <van-button type="info" style="border-radius:5px;" size="small" @click.native="addPersonMessage">新增人员</van-button>
          <van-button type="primary" style="border-radius:5px;" size="small" @click="updateQuarantine">解除隔离</van-button>
        </div>
      </van-tabbar>
      <div style="width:100%;height:100px;" :class="[showTitlePaddingTop?'title-message':'']" />
    </div>
    <van-popup v-model="changeShow" position="bottom" :style="{ height: '50%' }">
      <van-search
        v-if="true"
        v-model="titleValue"
        show-action
        placeholder="请输入隔离点名称"
        @search="onSearchTitle"
      >
        <template #action>
          <div @click="onSearchTitle">搜索</div>
        </template>
      </van-search>
      <van-picker
        title="隔离点"
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="onCancel"
        @change="onChangeLocation"
      />
    </van-popup>
    <van-dialog v-model="showTime" title="解除隔离时间" show-cancel-button @confirm="confirmRemove">
      <div class="remove-time">{{ dateFormat("YYYY-mm-dd HH:MM:SS", new Date()) }}</div>
    </van-dialog>

    <van-dialog v-model="showClockTime" title="签到时间" show-cancel-button @confirm="confirmTime">
      <div class="remove-time">{{ dateFormat("YYYY-mm-dd HH:MM:SS", new Date()) }}</div>
    </van-dialog>
  </div>
</template>
<script>
import Vue from 'vue'

import { Toast, Dialog, Icon, List } from 'vant'
import { PullRefresh } from 'vant'
import { SwipeCell } from 'vant'
import { Search } from 'vant'
import { Tabbar, TabbarItem } from 'vant'
import { Checkbox, CheckboxGroup } from 'vant'
import { Button } from 'vant'
import { Empty } from 'vant'
import { Picker } from 'vant'
import { Popup } from 'vant'

Vue.use(Popup)
Vue.use(Picker)
Vue.use(Empty)
Vue.use(Button)
Vue.use(Checkbox)
Vue.use(CheckboxGroup)
Vue.use(Tabbar)
Vue.use(TabbarItem)
Vue.use(Search)
Vue.use(SwipeCell)
Vue.use(PullRefresh)
Vue.use(Toast).use(Dialog).use(Icon).use(List)
import $api from '@/api/index'

import { mapGetters } from 'vuex'
export default {
  name: 'Applicationcode',
  beforeRouteLeave(to, from, next) {
    sessionStorage.setItem('scrollH', document.getElementById('content').scrollTop)
    next()
  },
  data() {
    return {
      list: [],
      listText: '暂无数据...',
      loading: false,
      finished: false,
      refreshing: false,
      obj: {
        pageNum: 1,
        pageSize: 10,
        createId: '',
        name: ''
      },
      deleteId: '',
      active: 1,
      result: [],
      changeShow: false,
      objs: {
        createId: '',
        reportId: '',
        updateId: ''
      },
      clockState: false,
      showTime: false,
      value: '',
      showClockTime: false,
      reportInfo: [],
      objMessage: {
        pageNum: 1,
        pageSize: 1000
      },
      columns: [],
      title: '',
      titleValue: ''

    }
  },
  computed: {
    ...mapGetters([
      'reportId',
      'reportName',
      'parentName',
      'createId'
    ]),
    showTitlePaddingTop() {
      return this.$store.state.user.showTitlePaddingTop
    }
  },

  beforeCreate() {
    this.$store.dispatch('user/showView', this.$route.name)

    this.$dd.hideTitleBar()
    console.log(this.$store)
  },
  activated() {
    if (this.$route.query.title) {
      this.title = this.$route.query.title
    }
    this.$dd.hideTitleBar()
    this.$dd.setTitle({
      title: ''
    }).then(res => {
      console.log(res)
    }).catch(err => { console.log(err) })
    if (this.$store.state.user.refresh) {
      if (sessionStorage.getItem('keepAlive')) {
        sessionStorage.setItem('keepAlive', false)
        this.list = []
      }
      this.pageInfoList()
    }
    if (sessionStorage.getItem('scrollH')) {
      document.getElementById('content').scrollTop = sessionStorage.getItem('scrollH')
    }
    this.$store.dispatch('user/show', true)
  },
  mounted() {
    if (this.$route.query.title) {
      this.title = this.$route.query.title
    }
    this.$nextTick(() => {
      document.getElementsByClassName('van-nav-bar__placeholder')[0].style.height = '40px'
    })
    if (this.$until.h5userAgent() === 1) {
      this.$store.dispatch('user/showTitle', true)
    }
    this.getCountMessage()
    this.$dd.ready(() => {
      this.$dd.hideTitleBar()
      this.$dd.setTitle({
        title: ''
      }).then(res => {
        console.log(res)
      }).catch(err => { console.log(err) })
    })
    this.pageInfoList()
    this.queryClickState()
    this.$store.dispatch('user/show', true)
    this.$refs.order.style.height = '100%'
  },
  beforeDestroy() {
  },
  methods: {
    goback() {
    },
    onSearch() {
      this.obj.name = this.value
      this.list = []
      this.pageInfoList()
    },
    getData() {},
    addPersonMessage() {
      this.$router.push({ path: '/code/index', query: {
        state: '1'
      }})
    },
    getCountMessage() {
      this.objMessage['phone'] = sessionStorage.getItem('phone')
      this.objMessage['employeeCode'] = sessionStorage.getItem('employeeCode')
      this.objMessage['reportName'] = this.titleValue
      $api.user.pageReportInfo(this.objMessage).then(res => {
        if (res.data.list.length !== 0) {
          res.data.list.forEach(res => {
            this.columns.push({
              text: res.organizationName,
              id: res.organizationCode,
              name: res.parentName

            })
          })
        }
      })
    },
    onChange(index) {
    },
    pageInfoList() {
      this.obj['reportId'] = this.reportId
      return new Promise(resolve => {
        $api.user.pageInfoList(this.obj).then(res => {
          if (this.refreshing) {
            this.list = []
            this.refreshing = false
          }
          if (res.data.list.length === 0) {
            this.list = []
          } else {
            this.list = this.list.concat(res.data.list)
          }

          const obj = {}
          this.list = this.list.reduce((cur, next) => {
            obj[next.id] ? '' : obj[next.id] = true && cur.push(next)
            return cur
          }, [])
          this.loading = false
          this.obj.pageNum = res.data.nextPage !== 0 ? res.data.nextPage : 1
          if (this.list.length >= res.data.total) {
            this.finished = true
          }
          resolve(this.list)
        }, error => {
          this.refreshing = false
          resolve([])
          console.log(error)
        })
      })
    },
    removeOrder() {
    },
    getPerson(id, arg) {
      sessionStorage.setItem('keepAlive', false)
      this.$store.dispatch('user/refresh', false)
      this.$router.push({ path: '/code/index', query: {
        id: id,
        state: arg
      }})
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.obj.pageNum = 1
      this.obj.pageSize = 10
      this.pageInfoList()
    },
    deleteInfo(id, index, arg) {
      if (!arg) {
        Toast('解除隔离人员不能删除!')
        return
      }
      this.deleteId = id
      Dialog.confirm({
        title: '删除',
        message: '确认删除?'
      })
        .then(() => {
          this.list.splice(index, 1)
          $api.user.deleteInfo({ id: this.deleteId, createId: this.createId }).then(res => {
            Toast('删除成功!')
          })
        })
        .catch(() => {
          // on cancel
        })
    },
    changeLocation() {
      this.changeShow = true
    },
    onConfirm(value, index) {
      Toast('更换隔离点成功')
      this.$store.dispatch('distanceInfo/setReportId', value.id)
      this.$store.dispatch('distanceInfo/setReportName', value.text)
      this.$store.dispatch('distanceInfo/setParentName', value.name)
      this.title = value.text
      this.result = []
      this.list = []
      this.pageInfoList()
      this.changeShow = false
    },
    onCancel() {
      this.changeShow = false
    },
    onChangeLocation() {},
    queryClickState() {
      this.objs.createId = this.createId
      this.objs.updateId = this.createId
      this.objs.reportId = this.reportId
      $api.user.queryClick(this.objs).then(res => {
        this.clockState = res.data
      })
    },
    updateQuarantine() {
      if (this.result.length === 0) {
        Toast('请选择解除隔离人员')
        return
      }
      this.showTime = true
    },
    queryClick() {
      this.showClockTime = true
    },
    confirmTime() {
      $api.user.clickClock(this.objs).then(res => {
        this.showClockTime = false
        Toast('健康签到成功')
        this.queryClickState()
      })
    },
    confirmRemove() {
      const arr = this.result
      $api.user.updateQuarantineStatus({ updateId: this.createId, ids: arr }).then(res => {
        this.result = []
        this.pageInfoList().then(res => {
          if (res.length !== 0) {
            for (let i = 0; i < res.length; i++) {
              for (let j = 0; j < arr.length; j++) {
                if (res[i].id.toString() === arr[j].toString()) {
                  this.$set(res[i], 'quarantStatus', 0)
                  this.$set(res[i], 'realTime', this.dateFormat('YYYY-mm-dd HH:MM:SS', new Date()))
                }
              }
            }
          }
        })
      })
    },
    dateFormat(fmt, date) {
      let ret
      const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString() // 秒
      }
      for (const k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
        }
      }
      return fmt
    },
    onSearchTitle() {
      this.getCountMessage()
    }
  }
}
</script>

<style lang="scss" scoped>
.applicationcode{
  width:100%;
  height:100%;
  .content{
    width:100%;
    height:100%;
    overflow-y: scroll;
    margin-top:10px;
    font-family: PingFangSC-Regular, PingFang SC;
  }
  .order-content{
    width:96%;
    margin:10px auto;
    margin-top:10px;
    box-sizing: border-box;
    padding:0px 20px 20px 20px;
    background-color:#ffffff;
    border-radius: 10px;
    font-family: PingFangSC-Medium, PingFang SC;
  }
  .order-color{
    background-color:rgba(119, 119, 119, 0.2)!important;
    color:rgba(119, 119, 119, 0.6)!important;
    .content-message{
       >div:nth-child(2){
         color:rgba(119, 119, 119, 0.6)!important;
       }
    }
    .edite{
      fill:rgba(119, 119, 119, 0.6)!important;
    }
  }
  .order-msg{
    margin-top:30px;
  }
  .title-message{
    padding-top:80px;
  }
  .content-time{
    display:flex;
    justify-content: space-between;
  }
  .chiooce-order{
    padding-right:20px;
  }
  .content-message{
    padding:20px 10px 10px 10px;
    display:flex;
    >div:nth-child(1){
      color:rgba(119, 119, 119, 0.6);
      font-size: 30px;
      flex:1.5;
    }
    >div:nth-child(2){
      padding-left:10px;
      color:rgba(65, 157, 244, 1);
      font-size: 30px;
      flex:3;
    }
  }
  .reson{
    display: flex;
  }
  .edite{
    width:40px;
    height:40px;
    color:rgba(65, 157, 244, 1);
    padding:10px;
    margin-right:20px;
  }
  .delete{
    width:40px;
    height:40px;
    padding:10px 0 10px 10px;
  }
  .remove-time{
    padding:40px 20px;
    text-align:center;
    width:100%;
  }
  .add{
    width:40px;
    height:40px;
  }
  .number{
    font-size:32px;
    font-weight:600;
    color:rgba(119, 119, 119, 1);
  }
  .order-title{
    border-bottom:1px solid rgba(229, 229, 229, 1);
    padding:10px 0;
    color:rgba(119, 119, 119, 0.6);
  }
  .content-footer{
    margin:20px 0;
  }
}
.title-message{
  ::v-deep .van-nav-bar--safe-area-inset-top{
    padding-top:80px!important;
    height:10px!important;
  }
}
.title-message ::v-deep .van-nav-bar__placeholder{
  height:40px!important;
}
.content-title{
  padding:40px 30px;
  font-size:14px;
  .confirm{
    color:#576b95;
  }
}
.cancel{}
</style>
